import Vue from 'vue'
import Store from './store.js'
import {
	playModeConfig
} from './config.js';
import {
	storage,
	storage_constants
} from "./StorageUtil.js"
import * as util from "./BaseUtil.js"
export default {
	extends: Store,
	data() {},
	methods: {
		initMusic() {
			let audioPlayer = null;
			/* #ifdef H5  */
			audioPlayer = uni.createInnerAudioContext();
			/* #endif */
			/* #ifdef APP-PLUS */
			audioPlayer = uni.getBackgroundAudioManager();
			/* #endif */
			audioPlayer.autoplay = false;

			audioPlayer.onTimeUpdate((e) => {
				this.setPlaySeconds(audioPlayer.currentTime);
				let progress = (audioPlayer.currentTime / audioPlayer.duration) * 100;
				if (progress) {
					this.setProgress(progress);
				}
				this.updateLrc(false);
			});

			audioPlayer.onCanplay(() => {
				this.setMusicIsReady(true);
			})
			audioPlayer.onError(()=>{
				util.showToast('播放错误，即将播放下一首');
				this.next();
			})

			audioPlayer.onEnded(() => {
				if (playModeConfig.single.id == this.playMode.id) {
					this.setMusic(this.playIndex, null, () => {
						this.play();
						this.setPlayState(true);
					});
				} else if (playModeConfig.random.id == this.playMode.id) {
					const index = parseInt((this.playList.length - 1) * Math.random())
					this.setMusic(index, null, () => {
						this.play();
						this.setPlayState(true);
					});
				} else {
					this.next();
				}
			})
			Vue.prototype.audioPlayer = audioPlayer;
			Vue.prototype.prev = this.prev;
			Vue.prototype.next = this.next;
			Vue.prototype.stop = this.stop;
			Vue.prototype.pause = this.pause;
			Vue.prototype.play = this.play;
			Vue.prototype.loadLrc = this.loadLrc;
			Vue.prototype.setMusic = this.setMusic;
			// Vue.prototype.getMusicPlayUrl = this.musicApi.getPlayUrl;
			// Vue.prototype.getLrc = this.musicApi.getLrc;
			// Vue.prototype.getMusicOtherInfo = this.musicApi.getMusicOtherInfo
			const playMode = storage.get(storage_constants.playMode);
			if (!playMode) {
				this.setPlayMode(playModeConfig.list);
			}
			const mySongList = storage.getArrayDefault(storage_constants.mySongList, []);
			/**
			 * 初始化歌词
			 */
			if (this.playList && this.playIndex >= 0) {
				let music = this.playList[this.playIndex];
				if (music) {
					this.loadLrc(music, () => {
						this.updateLrc(true);
					});
				}
			}
		},
		/**
		 * 设置音乐
		 * @param {Object} index
		 * @param {type} progress 
		 * @param {Object} call
		 */
		setMusic(index, progress, call) {
			if (this.playList && this.playList.length > 0) {
				if (index == null) {
					index = 0
				}
				// 停止播放
				this.audioPlayer.stop();
				// 更新播放状态
				this.setPlayState(false);
				if (progress) {
					// 重置进度条
					this.setProgress(progress.progress || 0)
					// 重置播放秒数
					this.setPlaySeconds(progress.playSeconds || 0)
				} else {
					// 重置进度条
					this.setProgress(0)
					// 重置播放秒数
					this.setPlaySeconds(0)
				}
				// 重置总秒数
				this.setTotalSeconds(0)

				// 音乐状态为未准备
				this.setMusicIsReady(false)
				let music = this.playList[index];
				/* this.getMusicOtherInfo(music,(musicOtherInfo)=>{
					music = musicOtherInfo;
					
				}) */

				const oldPlayMusic = this.playList[this.playIndex];
				if (!util.objEquals(oldPlayMusic, music)) {
					// 重置歌词
					this.setLrcs([{
						time: '[00:00.00]',
						content: '歌词加载中'
					}]);
					this.setLrc({
						time: '[00:00.00]',
						content: '歌词加载中'
					})
				}
				this.setPlayIndex(index);
				// 加载歌词
				this.loadLrc(music);
				// 获取播放地址
				Vue.prototype.getMusicPlayUrl && Vue.prototype.getMusicPlayUrl(music).then(playUrl => {
					console.log(`播放地址：${playUrl}`)
					this.audioPlayer.src = playUrl;
					this.audioPlayer.title = music.name;
					this.audioPlayer.singer = music.singer;
					this.audioPlayer.coverImgUrl = music.coverImg;
					let timer = setInterval(() => {
						if (this.musicIsReady) {
							this.setTotalSeconds(this.audioPlayer.duration)
							if (this.playSeconds > 0) {
								this.audioPlayer.seek(this.playSeconds)
							}
							this.setMusicIsReady(false)
							clearInterval(timer);
							if (call) {
								call();
							}
						}
					}, 200);
				})
			}
		},
		getMusicOtherInfo(music, call) {
			if (music.loadOtherInfo) {
				Vue.prototype.getMusicOtherInfo && Vue.prototype.getMusicOtherInfo(music).then(musicResult => {
					call(musicResult)
				})
			}
		},
		/**
		 * 加载歌词
		 */
		loadLrc(music, call) {
			Vue.prototype.getLrc && Vue.prototype.getLrc(music).then(lrcStr => {
				if (lrcStr) {
					this.setLrcStr(lrcStr)
					if (call) {
						call();
					}
				} else {
					this.setLrcStr('[00:00.00]无歌词')
				}
			})
		},
		/**
		 * 更新当前歌词
		 * @param {Object} isInit
		 */
		updateLrc(isInit) {
			if (this.lrcs) {
				const sec = parseInt(this.playSeconds);
				let index = sec + 1;
				let line = this.lrcs[index];
				if (line) {
					this.setLrc(line);
				} else {
					if (isInit) {
						for (var i = index; i >= 0; i--) {
							let initLine = this.lrcs[i];
							if (initLine) {
								this.setLrc(initLine);
								break;
							}
						}
					}
				}

			}

		},
		/**
		 * 播放
		 */
		play() {
			this.audioPlayer.play();
			this.setPlayState(true);
			const music = this.playList[this.playIndex];
			this.pushRecentlyPlayList(music);
		},
		/**
		 * 暂停
		 */
		pause() {
			this.audioPlayer.pause();
			this.setPlayState(false);
		},
		/**
		 * 停止
		 */
		stop() {
			this.audioPlayer.stop();
			this.setPlayState(false);
			this.setProgress(0);
			this.setPlaySeconds(0)
		},
		/**
		 * 下一曲
		 */
		next() {
			const length = this.playList.length;
			let index = -1;
			if (this.playIndex == length - 1) {
				index = 0;
			} else {
				index = this.playIndex + 1;
			}
			this.setMusic(index, null, () => {
				this.play();
				this.setPlayState(true);
			});
		},

		/**
		 * 上一曲
		 */
		prev() {
			const length = this.playList.length;
			let index = this.playIndex;
			if (index == 0) {
				index = length - 1;
			} else {
				index = index - 1;
			}
			this.setMusic(index, null, () => {
				this.play();
				this.setPlayState(true);
			});
		},
		pushRecentlyPlayList(music){
			let recentlyPlayList = storage.getArrayDefault(storage_constants.recentlyPlayList, []);
			let index = util.findIndex(recentlyPlayList,music);
			if(index >= 0){
				recentlyPlayList.splice(index,1)
			}
			recentlyPlayList.splice(0,0,music)
			this.setRecentlyPlayList(recentlyPlayList);
			this.$forceUpdate()
		}
	}
}
